package com.hngy.java;

import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.rdd.RDD;

public class CreateRddByFileJava {

    public static void main(String[] args){
        //创建sparkContext
        SparkConf conf = new SparkConf();
        conf.setAppName("CreateRddByFileJava")
                .setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);
        //
        String path = "D:\\b.txt";
        path = "hdfs://hadoop001:9001/word.txt";

        //读取文件数据，可以在textFile中指定生成的RDD的分区数量
        JavaRDD<String> rdd = sc.textFile(path);

        //获取每一行数据的长度，计算文件内数据的总长度
        JavaRDD<Integer> lengthRDD = rdd.map(new Function<String, Integer>() {
            @Override
            public Integer call(String line) throws Exception {
                return line.length();
            }
        });
        Integer length = lengthRDD.reduce(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer i1, Integer i2) throws Exception {
                return i1 + i2;
            }
        });
        System.out.println(length);

        //停止sparkContext
        sc.stop();
    }
}
